# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : Flask 和 websockets结合.py
# @Author: dongguangwen
# @Date  : 2025-01-05 10:51
import asyncio
from flask import Flask
from threading import Thread
import websockets

app = Flask(__name__)


@app.route('/')
def index():
    return "WebSocket Server is running on ws://localhost:6789"


async def websocket_client(websocket, path):
    while True:
        try:
            message = await websocket.recv()
            print(f"Received: {message}")
            await websocket.send(f"Echo: {message}")
        except websockets.exceptions.ConnectionClosed:
            print("Connection closed")
            break


def start_websocket_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    start_server = websockets.serve(websocket_client, 'localhost', 6789)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()


if __name__ == '__main__':
    # 启动 WebSocket 服务器线程
    websocket_thread = Thread(target=start_websocket_server)
    websocket_thread.start()

    #  启动Flask服务器
    app.run(port=5000)
